from __future__ import with_statement
from oms.apps.system.models import Setting,Interface
import os
import re

SERVICE_DIRS=["/usr/local/etc/rc.d","/etc/rc.d"]
SERVICES=["postfix","dovecot"]

def set_rc_conf(key,value):
    rc_conf = open("/etc/rc.conf","r")
    rc_conf_new = open("/etc/rc.conf.new","w")
    found = False
    for line in rc_conf:
        if line.strip().startswith("#") or len(line.strip()) == 0: 
            rc_conf_new.write(line)
            continue
        old_key,old_value = line.split("=")
        if old_key.strip() == key.strip():
            old_value = '"' + value.strip() + '"\n'
            found = True
        rc_conf_new.write(old_key + "=" + old_value)
    if not found:
        rc_conf_new.write(key + '="' + value+'"\n') 
    rc_conf.close()
    rc_conf_new.close()
    os.system("mv /etc/rc.conf.new /etc/rc.conf")
    return True

def unset_rc_conf(key):
    rc_conf = open("/etc/rc.conf","r")
    rc_conf_new = open("/etc/rc.conf.new","w")
    for line in rc_conf:
        if line.strip().startswith("#") or len(line.strip()) == 0: 
            rc_conf_new.write(line)
            continue
        old_key,old_value = line.split("=")
        if old_key.strip() == key.strip():
            continue       
        else:
            rc_conf_new.write(line)
    rc_conf.close()
    rc_conf_new.close()
    os.system("mv /etc/rc.conf.new /etc/rc.conf")
    return True

def get_rc_conf(search_key):
    with open("/etc/rc.conf","r") as rc_conf:
        for line in rc_conf:
            if line.strip().startswith("#") or len(line.strip()) == 0: 
                continue
            key,value = line.split("=",1)
            if key.strip() == search_key.strip():
                value = value.strip()
                if value.startswith('"') and value.endswith('"'):
                    value = value[1:-1]
                return value
    return ""

def generate_hosts():
    hostname = Setting.objects.get(key="hostname").value
    domain = Setting.objects.get(key="domain").value
    hosts = open("/etc/hosts","w")
    hosts.write("127.0.0.1 localhost %s\n" % (hostname+"."+domain))
    hosts.close()
    
def generate_resolv_conf():
    primary_dns = Setting.objects.get(key="primary_dns").value
    secondary_dns = Setting.objects.get(key="secondary_dns").value
    resolv_conf = open("/etc/resolv.conf","w")
    if primary_dns.strip() != "":
        resolv_conf.write("nameserver "+primary_dns+"\n")
    if secondary_dns.strip() != "":
        resolv_conf.write("nameserver "+secondary_dns+"\n")
    resolv_conf.close()

def get_hostname():
    hostname_domain =get_rc_conf("hostname")   
    if hostname_domain.find(".") > -1:
        return hostname_domain.split(".",1)[0]
    else:
        return hostname_domain

def get_domain():
    hostname_domain =get_rc_conf("hostname")   
    if hostname_domain.find(".") > -1:
        return hostname_domain.split(".",1)[1]
    else:
        return ""

def set_hostname():
    hostname = Setting.objects.get(key="hostname").value
    domain = Setting.objects.get(key="domain").value
    set_rc_conf("hostname",hostname+"."+domain)
    os.system("hostname %s" % hostname +"." + domain)
    generate_hosts()
    return True

def get_dns():
    nameservers=[]
    with open("/etc/resolv.conf") as resolv_conf:
        for line in resolv_conf:
            if line.strip().startswith("nameserver"):
                nameservers.append(line.split()[1])
    return nameservers

def set_dns():
    generate_resolv_conf()
    return True

def get_default_gateway():
    return get_rc_conf("defaultrouter")

def set_default_gateway():
    default_gateway = Setting.objects.get(key="gateway").value
    set_rc_conf("defaultrouter",default_gateway)
    os.system("/etc/rc.d/routing restart")
    return True

def get_interfaces():
    interfaces = os.popen("/sbin/ifconfig -l").read().split()
    interfaces.remove("lo0")
    return interfaces

def get_interface_dhcp(interface):
    config = get_rc_conf("ifconfig_%s" % interface)
    if config:
        return config == 'DHCP'
    else:
        return False

def get_interface_enabled(interface):
    config = get_rc_conf("ifconfig_%s" % interface)
    return not config == ""

def get_interface_ip(interface):
    config = get_rc_conf("ifconfig_%s" % interface)
    if config and not config == "DHCP":
        return config.split()[1]
    else:
        return ""

def get_real_interface_ip(interface):
    output = os.popen("ifconfig %s" % interface).read()
    ip = re.findall("(?<=inet )([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])",output)
    if len(ip) == 1:
        return ".".join(ip[0])
    else:
        return None

def get_interface_mask(interface):
    config = get_rc_conf("ifconfig_%s" % interface)
    if config and not config == "DHCP":
        return config.split()[3]
    else:
        return ""


def set_interface(name):
    interface = Interface.objects.get(name=name)
    if interface.enabled:
        if interface.dhcp:
            set_rc_conf("ifconfig_%s" % interface.name,"DHCP")
        else:
            set_rc_conf("ifconfig_%s" % interface.name,"inet %s netmask %s" % (interface.ip,interface.mask))
    else:
        unset_rc_conf("ifconfig_%s" % interface.name)
    os.system("/etc/rc.d/netif restart")
    return True

def service_enable(service):
    set_rc_conf("%s_enable" % service,"YES")

def service_disable(service):
    set_rc_conf("%s_enable" % service,"NO")

def service_enabled(service):
    print get_rc_conf("%s_enable" % service) 

def service_stop(service):
    for dir in SERVICE_DIRS:
        if os.path.exists("%s/%s" % (dir,service)):
            os.system("%s/%s stop" % (dir,service))
            break

def service_start(service):
    for dir in SERVICE_DIRS:
        if os.path.exists("%s/%s" % (dir,service)):
            os.system("%s/%s start" % (dir,service))
            break

def service_restart(service):
    for dir in SERVICE_DIRS:
        if os.path.exists("%s/%s" % (dir,service)):
            os.system("%s/%s restart" % (dir,service))
            break

def service_running(service):
    for dir in SERVICE_DIRS:
        if os.path.exists("%s/%s" % (dir,service)):
            print os.popen("%s/%s status" % (dir,service)).read().find("is running") > -1 and "YES" or "NO"

